package cn.com.qingz.core.utils;

import java.io.*;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;

import cn.com.qingz.core.exception.DicmfException;

/**
 * 七牛云存储存储器
 */
public class QiNiuStorage extends QiNiuTool  {

    private HttpClient httpClient = HttpClientBuilder.create().build();

    private static String AK = "lfECzeWMKQp0wsroqHTNdlXZ824aIcIAsflF7fdk" ;
    private static String SK = "9MiEFdsBOSzo0cyZz8mrnK5r7PgyaBD9oOUcCSTL" ;

    public QiNiuStorage() {
    }
/**
    public static void main(String[] args) throws IOException {
        QiNiuStorage storage = new QiNiuStorage();
//        storage.setBucket("yufei");
//        storage.setAuth(Auth.create("SbeVK-QzGJctDfPfg-eqFMksKbkMqv9MS9EJtncm", "qzs3h-k5pBPRPVmtFHfdTTOK2GV-Ne-hXXjvClWq"));
//        storage.setExpires(3600);
//        storage.setHost("7xj7ye.com1.z0.glb.clouddn.com");
//
        BucketManager bucketManager = new BucketManager(Auth.create("SbeVK-QzGJctDfPfg-eqFMksKbkMqv9MS9EJtncm", "qzs3h-k5pBPRPVmtFHfdTTOK2GV-Ne-hXXjvClWq"));
        FileListing fileListing = bucketManager.listFiles("yufei", "industry_", null, 1000, null);
//
//
//
        UploadManager uploadManager = new UploadManager();
//        
//    	<bean id="qiniu.config" class="mobi.meihuo.tool.storage.QiNiuTool.Config" p:accessKey="TUizr3jIriuBkDjKMoeCAkm_3kz9X8j8uq7mJ6z4" p:secretKey="moPCL9PlbBRHIxkEXU-wk-0pHkdIm2WehqoIpBZo"
//  			  p:bucket="meihuo-test" p:host="7xju3b.com2.z0.glb.qiniucdn.com" p:expires="3600"/>
//
//
        for (FileInfo fi :  fileListing.items) {
            System.out.println(fi.key + " _ " + fi.hash);
//            bucketManager.move("yufei", fi.key, "meihuo-test", fi.key);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(storage.retrieve(fi.key), baos);
//            System.out.println(new File(fi.key).getAbsolutePath());
//            FileUtils.write(new File(fi.key), baos.toByteArray());
            String token = Auth.create("TUizr3jIriuBkDjKMoeCAkm_3kz9X8j8uq7mJ6z4","moPCL9PlbBRHIxkEXU-wk-0pHkdIm2WehqoIpBZo")
                    .uploadToken("meihuo-basic", fi.key, 3600 , null);
            Response response = uploadManager.put(baos.toByteArray(), fi.key, token);
            Result result = response.jsonToObject(Result.class);
            System.out.println(result.getKey());
        }

        System.out.println(storage.store(new FileInputStream("E:/pic/yufei.jpg")));

      
        System.out.println(storage.delete("FgE9DMf2vH7-Pel8eCIES3ytwtQV"));
        
        InputStream is = storage.retrieve("Fi92_qesE_EBCfdkf_xGWyViO0Mi");
        FileOutputStream fos = new FileOutputStream(new File("e:/test.jpg"));
        IOUtils.copy(is, fos);
        
    }
**/

    public static void main(String[] args) throws FileNotFoundException, QiniuException {
        QiNiuStorage storage = new QiNiuStorage();
        Config conf = new Config();
        conf.setAccessKey("lfECzeWMKQp0wsroqHTNdlXZ824aIcIAsflF7fdk");
        conf.setBucket("codeblue-images");
        conf.setExpires(200000);
        conf.setSecretKey("9MiEFdsBOSzo0cyZz8mrnK5r7PgyaBD9oOUcCSTL");
        conf.setHost("7xl6wk.com1.z0.glb.clouddn.com");
        storage.setConfig(conf);

        storage.store(new FileInputStream("D:/love.jpg"));
       // http://7xl6wk.com1.z0.glb.clouddn.com/FrJ0gcjcPFPKivsa1IBZwzQuOBCz
        //<hash = FrJ0gcjcPFPKivsa1IBZwzQuOBCz, key = FrJ0gcjcPFPKivsa1IBZwzQuOBCz>


    //    storage.delete("FrJ0gcjcPFPKivsa1IBZwzQuOBCz");

        //lfECzeWMKQp0wsroqHTNdlXZ824aIcIAsflF7fdk:35gf026x7O6_d3bS2RGrsrAsulE=:eyJzY29wZSI6ImNvZGVibHVlLWltYWdlcyIsImRlYWRsaW5lIjoxNDU3MTg2NzM2fQ==



//这里是JS的上传的代码
//        <html>
//        <head lang="en">
//        <meta charset="UTF-8">
//        <title></title>
//        <link rel="stylesheet" href="css/lipe.css"/>
//        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
//        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
//                <!--[if lt IE 9]>
//        <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
//        <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
//        <![endif]-->
//        </head>
//        <body>
//        <!-- top-->
//        <form method="post" action="http://upload.qiniu.com/"
//        enctype="multipart/form-data">
//        <input name="key" type="hidden" value="wangdada">
//        <input name="x:okey" type="hidden" value="fff">
//        <input name="token" type="hidden" value="lfECzeWMKQp0wsroqHTNdlXZ824aIcIAsflF7fdk:35gf026x7O6_d3bS2RGrsrAsulE=:eyJzY29wZSI6ImNvZGVibHVlLWltYWdlcyIsImRlYWRsaW5lIjoxNDU3MTg2NzM2fQ==">
//        <input name="file" type="file" />
//
//        <input type="submit"  value="提交"/>
//        </form>
//        </body>
//        </html>
    }
    
    public String store(InputStream inputStream) {
        try {
            String token = auth.uploadToken(config.getBucket(), null, config.getExpires() , null);
            System.out.println(token);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(inputStream, baos);
            Response response = uploadManager.put(baos.toByteArray(), null, token);
            Result result = response.jsonToObject(Result.class);
            logger.debug("hash = {}, key = {}", result.getHash(), result.getKey());
            return result.getKey();
        } catch (Exception e) {
            throw new DicmfException(e);
        }
    }

    
    public InputStream retrieve(String s) {
        try {
            HttpResponse httpResponse = httpClient.execute(new HttpHost(config.getHost()), new HttpGet("/" + s));
            return httpResponse.getEntity().getContent();
        } catch (IOException e) {
            throw new    DicmfException(e);
        }
    }

    
    public boolean delete(String s) {
        try {
            bucketManager.delete(config.getBucket(), s);
            return true;
        } catch (QiniuException e) {
            e.printStackTrace();
//            LogUtils.error(e, logger);
            return false;
        }
    }

    public void copyBucket(Auth to, String toBucket) {
        BucketManager bucketManager = new BucketManager(auth);
        FileListing fileListing = null;
        try {
            fileListing = bucketManager.listFiles(config.getBucket(), null, null, 100, null);
            for (FileInfo fi :  fileListing.items) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                IOUtils.copy(retrieve(fi.key), baos);
                String token = to.uploadToken(toBucket, fi.key, config.getExpires(), null);
                uploadManager.put(baos.toByteArray(), fi.key, token);
            }
        } catch (Exception e) {
            throw new   DicmfException(e);
        }
    }
}
